package com.weiiew.backend.executor;

import com.weiiew.backend.entity.config.RecorderConfig;
import com.weiiew.backend.entity.enums.ExecutorState;
import com.weiiew.backend.operationUtils.OperationRecorder;
import com.weiiew.backend.operationUtils.OperationSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

/**
 * 脚本录制的执行器
 *
 * @author 魏锴
 * @since 2025/4/29
 */
@Component
public class RecorderExecutor {
    @Autowired
    private OperationRecorder recorder;

    private final Object lock = new Object(); // 用于在执行操作转化时保证不会相互干扰
    @Autowired
    protected SimpMessagingTemplate messagingTemplate;

    public OperationSequence getOperationSequence() {
        synchronized (lock) {
            return recorder.getRecordedSequence();
        }
    }

    public void initResource(RecorderConfig config) {
        recorder.setLogger(messagingTemplate, config.getChannel());
    }

    public void toggle() {
        synchronized (lock) {
            if (recorder.getState() == ExecutorState.PAUSE) recorder.start();
            else recorder.pause();
        }
    }

    public void reset() {
        synchronized (lock) {
            recorder.reset();
        }
    }
}
